package com.founder.helloworldapp;

import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;

public class GPSManager {
	
	private boolean stop;
	
	private LocationManager locationManager;
	
	private GPSLocationListener listener;
	
	private LocationListener gpsListener=null;
	
	private LocationListener networkListner=null;
	
	private Location currentLocation = null;
	
	//private Context context;
	
	public GPSManager(Context context) {
		//this.context = context;
		//获取到LocationManager对象
		locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
		networkListner=new MyLocationListener();
		gpsListener=new MyLocationListener();
		stop = true;
	}
	
	private void registerLocationListener() {
		locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10000, 10, networkListner);
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 10, gpsListener);
	}
	
	public void setListener(GPSLocationListener listener) {
		this.listener = listener;
	}
	
	public void start() {
		if (stop) {
			stop = false;
			registerLocationListener();
			requestLocation();
		}
	}
	
	public void stop() {
		if (!stop) {
			stop = true;
			removeLocation();
		}
	}
	
	public void restart() {
		stop();
		start();
	}
	
	private void removeLocation() {
		locationManager.removeUpdates(networkListner);
		locationManager.removeUpdates(gpsListener);
	}
	
	private void requestLocation() {
		//获取最后一次位置信息
		while (true) {
			Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
			if (location != null) {
				//currentLocation = location;
				if (listener != null) {
					listener.update(location, null);
				}
				break;
			}
			try {
				Thread.sleep(10000);
			} catch (InterruptedException e) {
				Log.w("Location", e.getMessage());
			}
		}
	}
	
	private void changeProvider(String provider) {
		/*
		Criteria criteria = new Criteria();
		criteria.setAccuracy(Criteria.ACCURACY_FINE); // 高精度
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setCostAllowed(true);
        criteria.setPowerRequirement(Criteria.POWER_LOW); // 低功耗
        */
		 //创建一个Criteria对象
		 Criteria criteria = new Criteria();
		 //设置粗略精确度
		 criteria.setAccuracy(Criteria.ACCURACY_COARSE);
		 //设置是否需要返回海拔信息
		 criteria.setAltitudeRequired(false);
		 //设置是否需要返回方位信息
		 criteria.setBearingRequired(false);
		 //设置是否需要返回速度信息
		 criteria.setSpeedRequired(false);
		 //设置是否允许付费服务
		 criteria.setCostAllowed(true);
		 //设置电量消耗等级
		 criteria.setPowerRequirement(Criteria.POWER_HIGH);
		 
		 //根据设置的Criteria对象，获取最符合此标准的provider对象
		 String defaultProvider = locationManager.getBestProvider(criteria, true);
		 Log.d("Location", "default Provider: " + defaultProvider);
		 //this.provider = defaultProvider;
	}
	
	// 创建位置监听器
	private class MyLocationListener implements LocationListener {
		
		// 状态改变时调用
		public void onStatusChanged(String provider, int status, Bundle extras) {
			Log.d("Location", "onStatusChanged");
		}
		
		// provider启用时调用
		public void onProviderEnabled(String provider) {
			Log.d("Location", "onProviderEnabled");
		}
		
		// provider失效时调用
		public void onProviderDisabled(String provider) {
			Log.d("Location", "onProviderDisabled");
		}
		
		// 位置发生改变时调用
		public void onLocationChanged(Location newLocation) {
			Log.d("Location", "onLocationChanged");
			if (isBetterLocation(newLocation, currentLocation)) {
				if (listener != null) {
					listener.update(newLocation, currentLocation);
				}
				currentLocation = newLocation;
			}
		}
	};
	
	public interface GPSLocationListener {
		public void update(Location newLocation, Location oldLocation);
	}
	
	private static final int CHECK_INTERVAL = 1000 * 30;
	protected boolean isBetterLocation(Location location,
			Location currentBestLocation) {
		if (currentBestLocation == null) {
			// A new location is always better than no location
			return true;
		}
 
		// Check whether the new location fix is newer or older
		long timeDelta = location.getTime() - currentBestLocation.getTime();
		boolean isSignificantlyNewer = timeDelta > CHECK_INTERVAL;
		boolean isSignificantlyOlder = timeDelta < -CHECK_INTERVAL;
		boolean isNewer = timeDelta > 0;
 
		// If it's been more than two minutes since the current location,
		// use the new location
		// because the user has likely moved
		if (isSignificantlyNewer) {
			return true;
			// If the new location is more than two minutes older, it must
			// be worse
		} else if (isSignificantlyOlder) {
			return false;
		}
 
		// Check whether the new location fix is more or less accurate
		int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation
				.getAccuracy());
		boolean isLessAccurate = accuracyDelta > 0;
		boolean isMoreAccurate = accuracyDelta < 0;
		boolean isSignificantlyLessAccurate = accuracyDelta > 200;
 
		// Check if the old and new location are from the same provider
		boolean isFromSameProvider = isSameProvider(location.getProvider(),
				currentBestLocation.getProvider());
 
		// Determine location quality using a combination of timeliness and
		// accuracy
		if (isMoreAccurate) {
			return true;
		} else if (isNewer && !isLessAccurate) {
			return true;
		} else if (isNewer && !isSignificantlyLessAccurate
				&& isFromSameProvider) {
			return true;
		}
		return false;
	}
 
	/** Checks whether two providers are the same */
	private boolean isSameProvider(String provider1, String provider2) {
		if (provider1 == null) {
			return provider2 == null;
		}
		return provider1.equals(provider2);
	}

}
